package com.atsmart.app;

import java.io.File;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import cn.jpush.android.api.JPushInterface;

import com.atsmart.app.sql.SqlHelper;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.log.UserLog;
//import com.atsmart.log.UserLog;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.json.Gson;
/**
 * TODO 配置文件
 */
public class BizApp extends Application {
	/**
	 * @return 上送时间
	 */
	public long getSendtime() {
		if (sendtime == 0) {

			sendtime = System.currentTimeMillis();
		}
		return sendtime;
	}

	private static Gson gson;
	public static Gson getGson() {
		if(gson == null){
			gson = new Gson();
		}
		return gson;
	}
	
	/**
	 * @param sendtime 时间s
	 */
	public void setSendtime(long sendtime) {
		this.sendtime = sendtime;
	}

	private static BizApp instance;
	private static String IMSI;
	private static String OSVERSION;
	private static String APILEVEL;
	private static String APPVERSION;

	private int tab;
	private boolean networkEnabled = true;

	private Activity currentActivity;
	ScheduledExecutorService pool;
	private static String sdkVersion;
	private boolean hasLogin;
	private String uid;
	private String userName;
	private String shareDesc;
	private static SqlHelper sqlHelper;
	private boolean isExited;
	private boolean isChecking;
	private boolean isDevice_end = false;
	private boolean isDevice_start = false;
	private BDLocation currentLocation;
	private long curretTime;
	public LocationClient mLocationClient;
	public long sendtime = 0;
	public boolean start = false;
	public boolean end = false;
	public int num = 1;
	public Boolean visile = true;
	public Boolean isLocation = false;
	/***是否是否保持连接标志位*/
	public Boolean keeping = true;
	/**上次上传是否完成 true --上传完成  false --上传未完成*/
	public Boolean isfinish = true;
	/***多张图片上传是完成  一张图片上传未完成 不继续上传*/
	public boolean isSend = true;

	/**是否写入log文件*/
	public static boolean isWrite = false;
	private static final String TAG = "BizApp";
	
	public MyLocationListenner myListener = new MyLocationListenner();
	
	/**
	 * 监听函数，又新位置的时候，格式化成字符串，输出到屏幕中
	 */
	private class MyLocationListenner implements BDLocationListener {
	 
		public void onReceiveLocation(BDLocation ll) {
			if (ll != null) {
				//维度判断
				if (ll.getLatitude() > 0.0001) {
					BizApp.getInstance().setCurrentLocation(ll);//封装当前定位结果
					BizApp.getInstance().setCurretTime(System.currentTimeMillis());//封装当前时间
					isLocation = true;
					Log.i(TAG, "getmLocationClient 即将结束定位");
					mLocationClient.stop();// 结束定位

				}
			}
		}
		
		public void onReceivePoi(BDLocation poiLocation) {
			
		}
	}
	

	/**
	 * 发起定位
	 * @return
	 */
	public LocationClient getmLocationClient() {
		try {
			if (mLocationClient == null) {
				//LocationClientOption 用来设置定位方式，包括是否缓存，是否使用gps，时间间隔等
				mLocationClient = new LocationClient(this);
				//LocationClientOption 用来设置定位方式，包括是否缓存，是否使用gps，时间间隔等
				LocationClientOption option = new LocationClientOption();
				option.setOpenGps(true);  //设置使用GPS
				
				//设置网络优先级，首选GPS定位
				option.setPriority(LocationClientOption.GpsFirst); 
				option.setPoiExtraInfo(false);
				option.setScanSpan(500);//定时定位，500毫秒
				
				mLocationClient.setLocOption(option);
	
				//DBLocaitonListener 获取定位结果 
				mLocationClient.registerLocationListener(new BDLocationListener() {
					@Override
					//DBLocation 定位结果的封面，包含坐标和错误码等信息
					public void onReceiveLocation(BDLocation ll) {
						if (ll != null) {
							//维度判断
							if (ll.getLatitude() > 0.0001) {
								BizApp.getInstance().setCurrentLocation(ll);//封装当前定位结果
								BizApp.getInstance().setCurretTime(System.currentTimeMillis());//封装当前时间
								isLocation = true;
								Log.i(TAG, "getmLocationClient 即将结束定位");
								mLocationClient.stop();// 结束定位
	
							}
						}
	
					}
	
					@Override
					public void onReceivePoi(BDLocation arg0) {
						// TODO Auto-generated method stub
	
					}
	
				});
			}
		} catch (Exception e) {
//			Log.e("BizApp", "启动异常！");
		}
		return mLocationClient;
	}

	public void setmLocationClient(LocationClient mLocationClient) {
		this.mLocationClient = mLocationClient;
	}

	private String poi;

	@Override
	public void onCreate() {
		super.onCreate();
		instance = this;
		
		JPushInterface.setDebugMode(false); // 设置开启日志,发布时请关闭日志
		JPushInterface.init(this); // 初始化 JPush
		 
		if (isWrite) {
			UserLog log = UserLog.getInstance();
			log.createSucessFile();
			log.createUnIntent();
			log.createException();
			log.createSqlFile();
			log.createSqlException();
			log.createFilePosition();
			log.createApkInfo();
		}
		//打开数据库
		setSqlHelper(new SqlHelper(this, "atsmart", null,
				SqlHelper.getDBVersion()));

	}

	/**
	 * ScheduledExecutorService扩展了ExecutorService接口，提供时间排程的功能。
	 * ScheduledExecutorService的实现类，是ScheduledThreadPoolExecutor。
	 * ScheduledThreadPoolExecutor对象包含的线程数量是没有可伸缩性的，只会有固定数量的线程。
	 *  不过你可以通过其构造函数来设定线程的优先级，来降低定时任务线程的系统占用
	 * @return
	 */
	public ScheduledExecutorService getThreadPool() {
		if (pool == null)
			pool = Executors.newScheduledThreadPool(1);
		return pool;

	}

	public synchronized static BizApp getInstance() {
		if (instance == null) {
			instance = new BizApp();
		}
		return instance;
	}

//	public void setTab(int tab) {
//		this.tab = tab;
//	}
//
//	public int getTab() {
//		return tab;
//	}
	
	public boolean hasLogin() {
		return hasLogin;
	}

	public void setHasLogin(boolean hasLogin) {
		this.hasLogin = hasLogin;
	}

	public String getAppVersion() {
		// if (StringUtil.isEmptyOrNull(APPVERSION)) {
		// APPVERSION = getInstance().getResources().getString(
		// R.string.app_version);
		// }
		return APPVERSION;
	}

//	/**
//	 * @return 返回IMIS码 
//	 */
//	public String getIMSI() {
//		if(PrefsUtils.getIsImsi() == null || StringUtil.isEmptyOrNull(PrefsUtils.getIsImsi())){
//			if (StringUtil.isEmptyOrNull(IMSI)) {
//				TelephonyManager ts = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
//				IMSI = ts.getSubscriberId();
//			}
//			if(StringUtil.isEmptyOrNull(IMSI)){
//				PrefsUtils.setIsImsi("1");
//				TelephonyManager tm = (TelephonyManager) this .getSystemService(TELEPHONY_SERVICE);
//				String deviceId = tm.getDeviceId();
//				if(StringUtil.isEmptyOrNull(deviceId)){
//					return null;
//				}else{
//					return deviceId;
//				}
//			}else{
//				return IMSI;
//			}
//		}else{
//			try {
//				TelephonyManager tm = (TelephonyManager) this
//						.getSystemService(TELEPHONY_SERVICE);
//				IMSI = tm.getDeviceId();
//				return IMSI;
//			} catch (Exception e) {
//				return null;
//			}
//		}
//	}
	
	public String getIMSI() {
		try {
			TelephonyManager tm = (TelephonyManager) this
					.getSystemService(TELEPHONY_SERVICE);
			IMSI = tm.getDeviceId();
			return IMSI;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * @return android  SDK 版本号
	 */
	public String getOSCode() {
		if (StringUtil.isEmptyOrNull(APILEVEL)) {
			//APILEVEL = Build.VERSION.SDK;
			APILEVEL = String.valueOf(Build.VERSION.SDK_INT);
		}
		return APILEVEL;
	}

	/**
	 * @return android sdk 版本字符串
	 */
	public String getOSVersion() {
		if (StringUtil.isEmptyOrNull(OSVERSION)) {
			OSVERSION = Build.VERSION.RELEASE;
		}
		return OSVERSION;
	}

	/**
	 * @return 得到 Wifi 的MAC地址  
	 */
	public String getLocalMacAddress() {
		//获取WifiManager对象
		WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		//获取WifiInfo对象
		WifiInfo info = wifi.getConnectionInfo();
		return info.getMacAddress();
	}

	public void setCurrentActivity(Activity currentActivity) {
		this.currentActivity = currentActivity;
	}

	public Activity getCurrentActivity() {
		return currentActivity;
	}

	public void setNetworkEnabled(boolean networkEnabled) {
		this.networkEnabled = networkEnabled;
	}

	public boolean isNetworkEnabled() {
		return networkEnabled;
	}

	public String getSdkVersion() {
		if (StringUtil.isEmptyOrNull(sdkVersion)) {
			//sdkVersion = Build.VERSION.SDK;
			sdkVersion = String.valueOf(Build.VERSION.SDK_INT);
		}
		return sdkVersion;
	}

	public int getScreenWidth() {
		WindowManager windowManager = this.getCurrentActivity()
				.getWindowManager();
	/*	Display display = windowManager.getDefaultDisplay();
		return display.getWidth();*/
		DisplayMetrics metrics = new DisplayMetrics();
		windowManager.getDefaultDisplay().getMetrics(metrics);
		return metrics.widthPixels;
	}

	public int getScreenHeight() {
		WindowManager windowManager = this.getCurrentActivity()
				.getWindowManager();
		/*Display display = windowManager.getDefaultDisplay();
		return display.getHeight();*/
		DisplayMetrics metrics = new DisplayMetrics();
		windowManager.getDefaultDisplay().getMetrics(metrics);
		return metrics.heightPixels;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

	public String getUid() {
		return uid;// "100000353";
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	/**
     */
	public String getUserName() {
		return userName;
	}

	public String getShareDesc() {
		return shareDesc;
	}

	public String getFilePath() {
		String result = null;
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			result = Environment.getExternalStorageDirectory().getAbsolutePath().concat("/atsmart");
			File gggMarket = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "atsmart");
			if (!gggMarket.exists()) {
				gggMarket.mkdir();
			}
		} else {
			result = BizApp.getInstance().getFilesDir().getAbsolutePath();
		}

		return result;
	}

	/**
	 * @param sqlHelper 设置目标数据库
	 */
	public void setSqlHelper(SqlHelper sqlHelper) {
		BizApp.sqlHelper = sqlHelper;
	}

	/**
	 * @return 返回数据库对象
	 */
	public SqlHelper getSqlHelper() {
		return sqlHelper;
	}

	public void setExited(boolean isExited) {
		this.isExited = isExited;
	}

	public boolean isExited() {
		return isExited;
	}

	public void setChecking(boolean isChecking) {
		this.isChecking = isChecking;
	}

	public boolean isChecking() {
		return isChecking;
	}

	public boolean isDevice_end() {
		return isDevice_end;
	}

	public void setDevice_end(boolean isDevice_end) {
		this.isDevice_end = isDevice_end;
	}

	public boolean isDevice_start() {
		return isDevice_start;
	}

	public void setDevice_start(boolean isDevice_start) {
		this.isDevice_start = isDevice_start;
	}

	public String getPoi() {
		return poi;
	}

	public void setPoi(String poi) {
		this.poi = poi;
	}

	public boolean isWiFiActive() {
		WifiManager mWifiManager = (WifiManager) getInstance().getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
		int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();
		if (mWifiManager.isWifiEnabled() && ipAddress != 0) {
			return true;
		} else {
			return false;
		}
	}


	public boolean isServiceRun() {

		ActivityManager am = (ActivityManager) getInstance().getSystemService(
				Context.ACTIVITY_SERVICE);
		//List<RunningServiceInfo> list = am.getRunningServices(30);
//		List<RunningServiceInfo> list = am.getRunningServices(Integer.MAX_VALUE);
		List<RunningServiceInfo> list = null;
		try{
//			Log.e("TAG","Integer.MAX_VALUE: = " + Integer.MAX_VALUE);
			list = am.getRunningServices(100);
		}catch (Exception e) {
			list = am.getRunningServices(30);
		}
		for (RunningServiceInfo info : list) {

			if (info.service.getClassName().equals(
					"com.atsmart.app.service.CheckingService")) {
				return true;
			}
		}
		return false;
	}

	
	public boolean isHisServiceRun() {

		ActivityManager am = (ActivityManager) getInstance().getSystemService(
				Context.ACTIVITY_SERVICE);

		List<RunningServiceInfo> list = am.getRunningServices(30);

		for (RunningServiceInfo info : list) {
			if (info.service.getClassName().equals(
					"com.atsmart.app.service.HistoryService")) {
				return true;
			}
		}
		return false;
	}
	
	public ComponentName checkSer() {

		ActivityManager am = (ActivityManager) getInstance().getSystemService(
				Context.ACTIVITY_SERVICE);

		List<RunningServiceInfo> list = am.getRunningServices(30);

		for (RunningServiceInfo info : list) {

			if (info.service.getClassName().equals(
					"com.atsmart.app.service.HistoryService")) {
				return info.service;
			}
		}
		return null;
	}
	/**
	 * @param context
	 * @return
	 */
	public boolean isNetworkAvailable() {
		ConnectivityManager mgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] info = mgr.getAllNetworkInfo();
		if (info != null) {
			for (int i = 0; i < info.length; i++) {
				if (info[i].getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * @param context
	 * @return
	 */
	public boolean isWifiAvailable(Context context) {
		ConnectivityManager mgr = (ConnectivityManager) context
				.getSystemService(Context.WIFI_SERVICE);
		NetworkInfo[] info = mgr.getAllNetworkInfo();
		if (info != null) {
			for (int i = 0; i < info.length; i++) {
				if (info[i].getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * @return 返回纬度
	 */
	public double getLat() {
		return getCurrentLocation() == null ? 0.0 : getCurrentLocation()
				.getLatitude();
//		return 0.0;
	}

	/**
	 * @return 返回经度 
	 */
	public double getLon() {
		return getCurrentLocation() == null ? 0.0 : getCurrentLocation()
				.getLongitude();
//		return 0.0;
	}

	public long getLocTime() {
		return getCurrentLocation() == null ? 0 : curretTime;
	}

	public long getCurretTime() {
		return curretTime;
	}

	public void setCurretTime(long curretTime) {
		this.curretTime = curretTime;
	}

	public String getAddress() {
		StringBuffer sbf = new StringBuffer();
		// if(BizApp.getInstance().getCurrentLocation()!=null){
		// BDLocation bd=BizApp.getInstance().getCurrentLocation();
		// sbf.append(bd.getProvince());
		// sbf.append(","+bd.getCity());
		// sbf.append(","+bd.getDistrict());
		// sbf.append(","+bd.getAddrStr());
		// sbf.append(","+BizApp.getInstance().getPoi());
		// }
		return sbf.toString();
	}

	public BDLocation getCurrentLocation() {
		return currentLocation;
	}

	public void setCurrentLocation(BDLocation currentLocation) {
		this.currentLocation = currentLocation;
	}

	public void showMemory(){
		try{
			try{
				long getAvailMemory = BizApp.getInstance().getAvailMemory();
//				Log.e("TAG", "可用内存： = " + getAvailMemory/(1024*1024));
				if((getAvailMemory/(1024*1024)) > 0 && (getAvailMemory/(1024*1024)) < 20){
					Toast.makeText(getApplicationContext(), "可用内存小于20M,请及时清理", Toast.LENGTH_SHORT).show();
				}
			}catch (Exception e) {
			}
			String status = Environment.getExternalStorageState();
			if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
				try{
					long getSDAvailableSize = BizApp.getInstance().getSDAvailableSize();
//					Log.e("TAG", "SD卡存可用储空间： = " + getSDAvailableSize/(1024*1024));
					if((getSDAvailableSize/(1024*1024) > 0) && (getSDAvailableSize/(1024*1024) < 20)){
						Toast.makeText(getApplicationContext(), "SD卡可用储空间小于20M,请及时清理", Toast.LENGTH_SHORT).show();
					}
				}catch (Exception e) {
				}
			}
			 
		}catch (Exception e) {
		}
	}
		/** 获取android当前可用内存大小*/
	//  private String getAvailMemory() {
		public long getAvailMemory() {
	      ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
	      MemoryInfo mi = new MemoryInfo();
	      am.getMemoryInfo(mi);
	      // mi.availMem; 当前系统的可用内存
	     return mi.availMem;
	//      return Formatter.formatFileSize(getBaseContext(), mi.availMem);// 将获取的内存大小规格化
	  }


	  /**
	   * 获得sd卡剩余容量，即可用大小
	   * 
	   * @return
	   */
	  public long getSDAvailableSize() {
	          File path = Environment.getExternalStorageDirectory();
	          StatFs stat = new StatFs(path.getPath());
	          long blockSize = stat.getBlockSize();
	          long availableBlocks = stat.getAvailableBlocks();
	//          return Formatter.formatFileSize(context, blockSize * availableBlocks);
	          return blockSize * availableBlocks;
	  }

	  /**
	   * 获得机身内存总大小
	   * 
	   * @return
	   */
	  public String getRomTotalSize() {
	          File path = Environment.getDataDirectory();
	          StatFs stat = new StatFs(path.getPath());
	          long blockSize = stat.getBlockSize();
	          long totalBlocks = stat.getBlockCount();
	          return Formatter.formatFileSize(getApplicationContext(), blockSize * totalBlocks);
	  }
	
	  /**
	   * 获得机身可用内存
	   * 
	   * @return
	   */
	  public String getRomAvailableSize() {
	          File path = Environment.getDataDirectory();
	          StatFs stat = new StatFs(path.getPath());
	          long blockSize = stat.getBlockSize();
	          long availableBlocks = stat.getAvailableBlocks();
	          return Formatter.formatFileSize(getApplicationContext(), blockSize * availableBlocks);
	  }
	// public class MyLocationListenner implements BDLocationListener {
	// @Override
	// public void onReceiveLocation(BDLocation location) {
	// if (location == null)
	// return;
	// setCurrentLocation(location);
	// }
	//
	// public void onReceivePoi(BDLocation poiLocation) {
	// if (poiLocation == null) {
	// return;
	// }
	// if (poiLocation.hasPoi()) {
	// } else {
	// setPoi("");
	// }
	//
	// }
	// }

//	 public BDLocation getCurrentLocation() {
//	 return currentLocation;
//	 }
//	
//	 public void setCurrentLocation(BDLocation currentLocation) {
//	 this.currentLocation = currentLocation;
//	 }

}
